﻿/**
 * Created by Administrator on 2017/4/9.
 */

//API接口转换
var BASE_URL = '';
var TEST_URL = 'http://120.27.10.209';

var locationUrl = window.location.href;
var API_URL = '';
if(locationUrl.indexOf('127.0.0.1')>0 || locationUrl.indexOf('localhost')>0){
    API_URL = TEST_URL;
}else{
    API_URL = BASE_URL;
}

//商品信息
var GET_PRODUCTINFO_URL = '/api/product/search';
var GET_SINGLE_PRO_URL = '/api/product/get';
var GET_COMMENTS_URL = '/api/product/comments';
var TO_COMMENTS_URL = '/api/product/comment';
var DELETE_PRODUCT_URL = '/api/product/delete';
var PUBLISH_URL = '/api/product/publish';
var ADD_FAVORITE_URL = '/api/product/addFavorite';
var DEL_FAVORITE_URL = '/api/product/delFavorite';

//上传
var IMG_UPLOAD = '/api/image/upload2';
//用户
var GET_USER_INFO = '/api/user/profile';
var USER_PRODUCTS_URL = '/api/user/products';
var SMS_CODE_URL = '/api/user/sendSms';
var BIND_PHONE_URL = '/api/user/bind';
var ID_VERIFY_URL = '/api/user/idVerify';
var SHOP_VERIFY_URL = '/api/user/merchantVerify';
var FEEDBACKS_URL = '/api/user/feedbacks';
var PUBLISH_FEEDBACKS_URL = '/api/user/submitFeedback';
var DELETE_FEEDBACK_URL = '/api/user/delFeedback';
var FAVORITES_URL = '/api/user/favorites';
var UPDATE_SHOPURL = '/api/user/update';
var UPDATE_URL = '/api/product/update';

//公共接口
var WEIXIN_LOGIN_URL = '/api/user/login';
var GET_CATEGORYS_URL = '/api/category/list'; //获取分类
var GET_HOME_INFOS_URL = '/api/home/info';
var GET_SERVICES_URL = '/api/home/services';
var GET_CHILD_SERVICES_URL = '/api/home/services/children';


/**
 * 地址栏获取参数
 */

var GetQueryString = function(name)
{
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if(r!=null)return  unescape(r[2]); return null;
}
/**
 * 获取类目列表
 * @param type 全类别
 */
var getCategoryList = function(type,orderBy,categoryId){
    $.ajax({
        url:API_URL+GET_PRODUCTINFO_URL,
        type:'get',
        dataType:'jsonp',
        data:{type:type,orderBy:orderBy,categoryId:categoryId,page:0,pageSize:10},
        success:function(data){
            if(data.ok==true){
                var tpl = template('category_list_tpl',data);
                $('.shop-list').html(tpl);
                if(data.page.totalPage){
                    $('#totalPage').val(data.page.totalPage);
                }else{
                    $('#totalPage').val(0);

                }
                new Swiper('.shop-list .swiper-container', {
                    slidesPerView: 3,
                    spaceBetween: 10
                });
            }else{
                console.log('no data');
            }

        },
        error:function(data){
            $.alert(data.msg);
        }
    });

};
/**
 * 获取分类
 */
var getCateogrys = function(type){
    $.ajax({
        url: API_URL + GET_CATEGORYS_URL,
        type: 'get',
        dataType: 'jsonp',
        data:{type:type},
        success: function (data) {
            //分类拼接
            if(data.ok==true){
                var datas= data.result;
                var json = {};
                var arrs = [];
                for(var i = 0;i<datas.length;i++){
                    json = {title:datas[i].name,value:datas[i].id};
                    arrs.push(json);
                }
                arrs.push({title:'全类别',value:'0'});
                $("#getCategorys").select({
                    title: "选择分类",
                    items: arrs,
                    onChange: function(d) {
                        var type = $('#type_type').val();
                        getCategoryList(type,0,d.values);
                        $('#type_categoryId').val(d.values);
                        $('#getCategorys').find('.txt').html(d.titles);
                        var from = $('#type_from').val();
                        var params = {
                            type:type,
                            categoryId:d.values,
                            from:from,
                            orderBy:0
                        };
                        dropLoad.init(params);
                    }
                });
            }else{
                $.alert(data.msg);
            }
        },
        error:function(data){
            $.alert(data.msg);
        }
    });
};

var dropLoad = {
     page:1,
     pageSize:2,
     totalPage:$('#totalpage').val() || 1000,
     loadHtml:$('<div class="dropload-load f15"><span class="weui-loading"></span>正在加载中...</div>'),
     noDataHtml:$('<div class="dropload-noData">没有更多数据了</div>'),
     ajaxing:false,//判断是否加载完毕
     init:function(params){
         if ( this.totalPage == 1) {
             this.showNoData();
         }else{
             this.addScrollEvent(params);
         }
     },
     showNoData:function(){
         this.removeScrollEvent();
         $('.shop-list').append(this.noDataHtml);
     },
     removeScrollEvent:function(){
         $('.weui_tab_bd').off('scroll.shop');
     },
     addScrollEvent:function(params){
         var self = this;
         var $module = $('.shop-list');
         var scrolling = false, $window = $('.weui_tab_bd'), windowHeight = $window.height(), lastScrollTop = 0 ;
         $window.on('scroll.shop',function(){
             if( scrolling ) return;
             var nowScrollTop = $window.scrollTop();
             if( $window.scrollTop() <= lastScrollTop ) {
                 lastScrollTop = nowScrollTop;
                 return;
             }
             lastScrollTop = nowScrollTop;
             //正在查看下面的内容
             scrolling = true;
             setTimeout(function(){
                 var scrollTop    = $window.scrollTop(); //模块相对视图区域的坐标
                 var top = $('.shop-list').position().top + 450;
                 var heightModule = $module.height();      //发现模块的高度
                 var viewHeight = scrollTop+windowHeight;
                 if( ( heightModule + top - viewHeight ) < 50 ){ //发现模块被容器隐藏的内容区域 小于50的时候
                     self.getNextData(params);
                 }
                 //}
                 scrolling = false;
             }, 20 );
         })
     },
     handleData:function(data){
         var self = this;
         var tpl = '';
         $.each(data,function(i,item){
             var imgs = item.images;
             tpl +='<div class="shop-item" categoryid="'+item.categoryId+'"><div class="shop-head"><div class="title">'+item.categoryName+'</div>'+
                 '<span class="fr">￥'+item.price+'</span></div><div class="swiper-container"><div class="swiper-wrapper">';
             for(var j=0;j<imgs.length;j++){
                 tpl += '<div class="swiper-slide"><a href=detail.html?id='+item.id+'><img data-img="'+imgs[j].smallUrl+'" src="'+imgs[j].smallUrl+'" /></a></div>';
             }
             tpl+='</div></div><div class="des-info">'+item.desc+'</div>'+
                 '<div class="fav-message"><a href="#">收藏<em>'+item.favoriteCount+'</em></a><a href="#">留言<em>'+item.commentCount+'</em></a>'+
                 '</div></div>';
         });
         $('.shop-list').append(tpl);
         if(self.totalPage == self.page){
             self.showNoData();
         }
         //slider
         new Swiper('.shop-list .swiper-container', {
             slidesPerView: 3,
             spaceBetween: 10
         });
         //图片懒加载
         var lazyloadImg = new LazyloadImg({
             el: '.shop-list [data-img]', //匹配元素
             top: 50, //元素在顶部伸出长度触发加载机制
             right: 50, //元素在右边伸出长度触发加载机制
             bottom: 50, //元素在底部伸出长度触发加载机制
             left: 50, //元素在左边伸出长度触发加载机制
             qriginal: false, // true，自动将图片剪切成默认图片的宽高；false显示图片真实宽高
             load: function(el) {
                 el.style.cssText += '-webkit-animation: fadeIn 01s ease 0.2s 1 both;animation: fadeIn 1s ease 0.2s 1 both;';
             },
             error:function(data){
                 $.alert(data.msg);
             }
         });

     },
    getNextData:function(params){
       var self = this;
       if(self.ajaxing == true) return;
       if(self.totalPage > self.page){
           self.loadHtml.appendTo('.shop-list');
           self.ajaxing = true;
           $.ajax({
               url:API_URL+GET_PRODUCTINFO_URL+'?page='+self.page+'&pageSize='+self.pageSize,
               type:'post',
               dataType:'jsonp',
               data:params,
               success:function(data){
                   self.ajaxing = false;
                   self.loadHtml.remove();
                   var datas = data.result;
                   if(datas && datas.length>0){
                       self.page = self.page + 1;
                       self.handleData(datas);
                       if(datas.length < self.pageSize){
                           self.totalPage = self.page;
                           self.showNoData();
                       }
                   }else{
                       self.totalPage = self.page;
                       self.showNoData();
                   }
               },
               error:function(){
                   self.ajaxing = false;
                   self.loadHtml.remove();
               }
           })
       }
    }
};

/**
 * 筛选
 */
var filter = function(){
    $("#resource").select({
        title: "选择来源",
        items: [
            {
                title:"不限",
                value:"0"
            },
            {
                title: "商家",
                value: "1"
            },
            {
                title: "个人",
                value: "2"
            }
        ],
        onChange: function(d) {
            var type = $('#type_type').val();
            var categoryId = $('#type_categoryId').val();
            $('#resource').find('span.txt').html(d.titles);
            getCategoryList(type,d.values,categoryId);
            $('#type_from').val(d.values);
        }
    });
};
var tabChange = function(){
    $('.weui_tabbar_item').on('click', function () {
        $(this).addClass('weui_bar_item_on').siblings('.weui_bar_item_on').removeClass('weui_bar_item_on');
        $(this).find('img.over').show();
        $(this).find('img.def').hide();
        $(this).siblings().find('img.over').hide();
        $(this).siblings().find('img.def').show();
    });
};

$(function(){
    tabChange();
    filter();
    var i = 0;
    $('#lastest').on('click',function(){
        var type = $('#type_type').val();
        var categoryId = $('#type_categoryId').val();
        i++;
        if(i%2==0){
            getCategoryList(type,0,categoryId);
        }
    });
    $('#price_sort').on('click',function(){
        var type = $('#type_type').val();
        var categoryId = $('#type_categoryId').val();
        i++;
        if(i%2==0){
            getCategoryList(type,1,categoryId);
            $('.icon-sortsvg').find('use').attr('xlink:href','#icon-sort-small1');
        }else{
            getCategoryList(type,2,categoryId);
            $('.icon-sortsvg').find('use').attr('xlink:href','#icon-sort-small2');
        }
    })
});


Array.prototype.remove = function (val) {
    var index = this.indexOf(val);
    if(index > -1){this.splice(index,1);}
};

//时间戳转日期
function formatDateTime(inputTime) {
    var date = new Date(inputTime);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d;
};
//浮点数校验
function checkDecimal(n){
    var decimalReg=/^\d{0,8}\.{0,1}(\d{1,2})?$/;
    if(decimalReg.test(n)){
        return true;
    }
    return false;
};

//登陆
var successUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx59435c8bafb97917&redirect_uri=http://dltt.youmoo.cn/wx1.0/wx_callback.html&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';


/**
 加载导航
 **/
function loadNav(){
    var navArr = {
        list:[
            {enName:'home',zh:"首页",url:'index.html'},
            {enName:'trade',zh:"买卖",url:'buy.html'},
            {enName:'news',zh:"资讯",url:'news.html'},
            {enName:'service',zh:"服务",url:'service.html'},
            {enName:'my',zh:"我的",url:'my_products_list.html'}
        ]
    };
    var isLogin = $.fn.cookie('isLogin');
    var tpl = template('nav_bar_tpl',navArr);
    $('#nav_bar').html(tpl);
    var index = $('#nav_bar').attr('index');
    if(index==0){
        $('#nav_bar a.weui_tabbar_item').eq(0).addClass('weui_bar_item_on');
        $.fn.cookie('publish_type','');
    }
    if(index==1){
        $('#nav_bar a.weui_tabbar_item').eq(1).addClass('weui_bar_item_on');
        $.fn.cookie('publish_type','');
    }
    if(index==2){
        $('#nav_bar a.weui_tabbar_item').eq(2).addClass('weui_bar_item_on');
        $.fn.cookie('publish_type','');
    }
    if(index==3){
        $('#nav_bar a.weui_tabbar_item').eq(3).addClass('weui_bar_item_on');
        $.fn.cookie('publish_type','');
    }
    if(index==4){
        if(isLogin){
            $('#nav_bar a.weui_tabbar_item').eq(4).addClass('weui_bar_item_on');
        }else{
            window.location.href = successUrl;
        }
    }
}
//获取地址栏参数
function GetQueryString(name)
{
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if(r!=null)return  unescape(r[2]); return null;
}
//获取中文参数
function getUrlParam(key) {
    // 获取参数
    var url = window.location.search;
    // 正则筛选地址栏
    var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
    // 匹配目标参数
    var result = url.substr(1).match(reg);
    //返回参数值
    return result ? decodeURIComponent(result[2]) : null;
}
//判断手机横竖屏状态：
window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", function() {
    if (window.orientation === 90 || window.orientation === -90 ){
        $.alert('请切换至竖屏状态，以便获得更佳的体验！');
    }
}, false);